var router ;
var $url_getWeixinJsConfig="/wechat/joins/sharetoken/10000.json";
var base_url="/";
//获取cookie中的用户id
var login_uid=0;
var login_token="";
var routeInfo;
var login_user_info=null;
var order_info=null;
var order_no="";
var longitude=114.0258336067;
var latitude=22.5360049867;
function makeShare(title,desc,link,imgUrl){
	wx.onMenuShareTimeline({
		title :"【"+ title+"】"+desc,
		link : link,
		imgUrl : imgUrl,
		success : function() {
			console.log("分享成功")
		}
	});
	wx.onMenuShareAppMessage({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功")
		},
		cancel : function() {
			console.log("取消分享")
		}
	});
	wx.onMenuShareQQ({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功")
		},
		cancel : function() {
			console.log("取消分享")
		}
	});
	wx.onMenuShareWeibo({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功")
		},
		cancel : function() {
			console.log("取消分享")
		}
	});
	wx.onMenuShareQZone({
		title : title,
		link : link,
		imgUrl : imgUrl,
		desc : desc,
		success : function() {
			console.log("分享成功")
		},
		cancel : function() {
			console.log("取消分享")
		}
	});
}

function go(url){
	window.location.href = url;
	//window.location.hash = url;
}
function goback(no){
	window.history.go(no);
}
function scrollTop(){
	//滚动条滚到顶部
	$("body").scrollTop(0);
}
function scrollTop2(){
	$('html, body').scrollTop(0);
}

/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 * @param {Object} fmt
 */
Date.prototype.format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if(/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}


/*时间格式化*/
formatDate = function(date, pattern) {
	//如果不设置，默认为当前时间
	if(!date) date = new Date();
	if(typeof(date) === "string") {
		if(date == "") date = new Date();
		else date = new Date(date.replace(/-/g, "/"));
	}
	/*补00*/
	var toFixedWidth = function(value) {
		var result = 100 + value;
		return result.toString().substring(1);
	};

	/*配置*/
	var options = {
		regeExp: /(yyyy|M+|d+|h+|m+|s+|ee+|ws?|p)/g,
		months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		weeks: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		weeksZh: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
	};

	/*时间切换*/
	var swithHours = function(hours) {
		return hours < 12 ? "AM" : "PM";
	};

	/*配置值*/
	var pattrnValue = {
		"yyyy": date.getFullYear(), //年份
		"MM": toFixedWidth(date.getMonth() + 1), //月份
		"dd": toFixedWidth(date.getDate()), //日期
		"hh": toFixedWidth(date.getHours()), //小时
		"mm": toFixedWidth(date.getMinutes()), //分钟
		"ss": toFixedWidth(date.getSeconds()), //秒
		"ee": options.months[date.getMonth()], //月份名称
		"ws": options.weeksZh[date.getDay()], //星期名称
		"M": date.getMonth() + 1,
		"d": date.getDate(),
		"h": date.getHours(),
		"m": date.getMinutes(),
		"s": date.getSeconds(),
		"p": swithHours(date.getHours())
	};

	return pattern.replace(options.regeExp, function() {
		return pattrnValue[arguments[0]];
	});
};
//增加天数
function dayAdd(nub,oldday){
	var date = new Date(oldday)
	date.setDate(date.getDate() + nub);
	return formatDate(date,"yyyy-MM-dd");
}

//获取表单数据
function getFormData(obj,id){
	var data = $(obj).find("#"+id).serializeArray();
	//console.log(data)
	var data_out={};
	$.each(data, function(ind,ele) {
		data_out[ele.name]=ele.value;
	});
	console.log(data_out)
	return data_out;
}


(function ($) {
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
})(jQuery);

function addBodyClass(className){
	if(!$("body").hasClass(className)){
		$("body").addClass(className)
	}
}
function removeBodyClass(className){
	$("body").removeClass(className)
}
function bindMobile(goto){
	//tpl_mobile
	$("body").append(template("tpl_mobile",{}));
	//锁屏
	$("#container").addClass("lock").css("height",$(window).height());
	$("#mobile_panel").on("click",".shadow",function(){
		$("#mobile_panel").remove();
		$("#container").removeClass("lock").css("height","auto");
	}).on("click","#btn_send_sms",function(){
		var mobile=$("#mobile_panel input[name='mobile']").val();
		//检查手机号
		if(!isMobile(mobile)){
			showErrorMsg("手机号格式不正确");
			return false;
		}
		djs.start(this);
		//发送短信
		ajaxPost("utils/sms/sendcode.json",{"phone":mobile,"type":7},function(data){
			showInfoMsg("发送成功，繁忙时段可能会有延时，请耐心等待",20000);
		})
	}).on("click","#btn_submit",function(){
		var mobile=$("#mobile_panel input[name='mobile']").val();
		var code=$("#mobile_panel input[name='code']").val();
		//检查手机号
		if(!isMobile(mobile)){
			showErrorMsg("手机号格式不正确");
			return false;
		}
		if(code==""){
			showErrorMsg("短信码错误");
			return false;
		}
		hideInfoMsg();
		showLoading("正在验证...");
		$.post("/account/bindmobile.json",{"phone":mobile,"smscode":code,"from":"web"},function(data){
			hideLoading();
			if(data.code==200){
				showInfoMsg("验证成功",2000);
				$("#mobile_panel").remove();
				$("#container").removeClass("lock").css("height","auto");
				setTimeout(function(){
					go(goto);
				},1500);
			}else{
				showErrorMsg(data.msg||"验证失败！");
			}
		})
	});
	$("#mobile_panel .mobile").focus();
}
//判断手机号
function isMobile(mobile){
	var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;  
  	if (!myreg.test(mobile)) {  
      	return false;  
  	} else {  
      	return true;  
  	}  
}
//返回空模板
function getCommonEmptyPage(){
	return template("tpl_empty",{})
}
/**
 * 10001 	正常
 * 10002	异常
 * 10003	空数据
 * 10005	时间超时
 * 
 * */
function ajaxGet(url,data,callback){
	//showLoading();
	data=data||{};
	data=$.extend({},data, {uid:login_uid,token:login_token});
	if(url.indexOf("http") == -1){
		url=base_url+url;
	}
	$.get(url,data,function(data){
		//hideLoading();
		if(data.code==200){
			if(callback){
				callback(data);
			}
		}else if(data.code!=404){
			showErrorMsg("服务器发生错误");
		}
	});
}
function ajaxPost(url,data,callback){
	showLoading();
	data=data||{};
	data=$.extend({},data, {uid:login_uid,token:login_token});
	if(url.indexOf("http") == -1){
		url=base_url+url;
	}
	$.post(url,data,function(data){
		hideLoading();
		if(data.code==200){
			if(callback){
				callback(data);
			}
		}else if(data.code!=404){
			showErrorMsg("服务器发生错误");
		}
	});
}


function showLoading(msg){
	if (!msg) {
		msg="数据加载中...";
	}
	var loadingHtml = template("func_loading",{msg:msg});
	if($("#loadingToast").length > 0){
		$("#loadingToast").show();
	}else{
		$("body").append(loadingHtml);
	}
}
function hideLoading(){
	 $('#loadingToast').fadeOut(100,function(){
	 	$(this).remove();
	 });
}

/**
 *显示错误信息 
 * */
function showErrorMsg(msg){
	var $tooltips = $('.js_tooltips');
	if ($tooltips.css('display') != 'none') return;
	$tooltips.html(msg);
	$tooltips.css('display', 'block');
    setTimeout(function () {
        $tooltips.css('display', 'none');
    }, 2000);
}
/**
 *显示一般信息 
 * */
function showInfoMsg(msg,t){
	if(!t){
		t=2000;
	}
	var $tooltips = $('.js_info_tooltips');
	if ($tooltips.css('display') != 'none') return;
	$tooltips.html(msg);
	$tooltips.css('display', 'block');
    setTimeout(function () {
        $tooltips.css('display', 'none');
    }, t);
}
function hideInfoMsg(){
	$('.js_info_tooltips').css('display', 'none');
}
/**
 * 倒计时
 * djs.start
 * */
var djs={
	element:null,
	time:60,
	time_left:60,
	oldText:"",
	stl:null,
	start:function(ele){
		var _this=this;
		this.element=$(ele);
		this.oldText=$(ele).html();
		$(ele).attr("disabled","disabled");
		this.stl=setInterval(function(){
			_this.time_left--;
			if(_this.time_left<1){
				clearInterval(_this.stl);
				_this.time_left=_this.time;
				_this.element.html(_this.oldText)
				$(ele).removeAttr("disabled");
			}else{
				_this.element.html(_this.time_left+"s后获取")
				//console.log(_this.time_left)
			}
		},1000);
	}
}

function numb2str(day_index){
	var day_names=["一","二","三","四","五","六","七","八","九","十"];
	var index_name="";
	//十以下 
	if(day_index < 11){
		return day_names[day_index-1];
	}
	//整十
	if(day_index % 10 == 0){
		if(day_index/10 ==1){
			return "十";
		}
		return  day_names[day_index/10-1]+"十";
	}
	//十到100
	index_name=day_names[parseInt(day_index/10)-1]+"十"+day_names[day_index % 10-1];
	
	return index_name;
}




/**
* @desc 根据两点间的经纬度计算距离
* @param {float} lat1 当前地点纬度值
* @param {float} lng1 当前地点经度值
* @param {float} lat2 目标地点纬度值
* @param {float} lng2 目标地点经度值
*/
function computeDistance(lat1,lng1,lat2,lng2) {
	//这个函数取两个坐标，一个起点坐标，一个终点坐标，并返回二者之间的距离（单位为千米）
    var startLatRads = degreesToRadians(lat1);
    var startLongRads = degreesToRadians(lng1);
    var destLatRads = degreesToRadians(lat2);
    var destLongRads = degreesToRadians(lng2);
	
    var Radius = 6371; // radius of the Earth in km
    var distance=Math.acos(Math.sin(startLatRads)*Math.sin(destLatRads) +
                 Math.cos(startLatRads) * Math.cos(destLatRads) *
                 Math.cos(startLongRads - destLongRads)) * Radius;
				 
    return distance.toFixed(2);
}
/**
 * 计算数字简写
 * */
function getNumberName(num){
	if(num<9000){
		return num;
	}else if(num < 90000){
		return (num/10000).toFixed(2)+"万";
	}else if(num < 9000000){
		return parseInt(num/10000)+"万";
	}else{
		return (num/100000000).toFixed(2)+"亿";
	}
}
function uploadWxImage(localId,callback){
	wx.uploadImage({
	    localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
	    isShowProgressTips: 1, // 默认为1，显示进度提示
	    success: function (res) {
	        var serverId = res.serverId; // 返回图片的服务器端ID
	        exchangeWxImage(serverId,callback);
	    }
	});
}
function initPreviewImg(obj){
	$(obj).on("click",".wx_img_preview",function(){
		var urls=[];
		curr=$(this).attr("src");
		$(this).parent().find("img.wx_img_preview").each(function(){
			urls.push($(this).attr("src"));
		})
		previewWxImage(curr,urls)
	})
}
function previewWxImage(curr,urls){
	wx.previewImage({
	    current: curr, // 当前显示图片的http链接
	    urls: urls // 需要预览的图片http链接列表
	});
}
